package kayao.client.network.login;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Vector;

import kayao.client.data.SharedMemory;
import kayao.common.*;

public class NotifyImNewTeamMate extends Thread {

	protected Client[] mMates;
	protected Vector<StrikeSender> mStrikeSenders=null;
	protected DatagramSocket mSocket=null;
	
	public NotifyImNewTeamMate(Client[] teamMates, DatagramSocket s) {
		mMates=teamMates;
		mSocket=s;
		mStrikeSenders=new Vector<StrikeSender>();

		//construct the strikers
		for(int i=0;i<mMates.length;i++)
		{
			if (mMates[i] != null) {
				if(mMates[i].getId()==SharedMemory.getInstance().getMyself().getId())
					continue;
				//size=10+lengthname
				byte []data=new byte[10+SharedMemory.getInstance().getMyself().getName().length()];
				//magic number
				NetworkUtils.insertIntToByteArray(data,0,KayaoValues.MAGIC_NUMBER);
				//msg id
				data[4]=KayaoValues.NEW_MATE_ARRIVED;
				//id
				NetworkUtils.insertIntToByteArray(data,5,SharedMemory.getInstance().getMyself().getId());
				//length
				data[9]=(byte)SharedMemory.getInstance().getMyself().getName().length();
				//name
				for(int j=0;j<SharedMemory.getInstance().getMyself().getName().length();j++)
					data[10+j]=(byte)SharedMemory.getInstance().getMyself().getName().charAt(j);
				
				try 
				{
					mStrikeSenders.add(new StrikeSender(mMates[i].getId(),
							new DatagramPacket(data,data.length,InetAddress.getByName(mMates[i].getIP()),
									KayaoValues.CLIENT_READ_PORT),mSocket,5000,3));
					//System.out.println("Created StrikeSender to: "+ mMates[i].getIP());
				} 
				catch (UnknownHostException e) {
					System.out.println("Error in I'm new Teammate thread: Unknown host: "+e.getMessage());
					e.printStackTrace();
				}
			}
		}
	}
	
	public void tell()
	{
		//send N hellos and wait for N answers
		//retry with hellos without answer X times
		while(!allAnswered())
		{
			//get the next client strike sender
			StrikeSender ss=mStrikeSenders.get(0);
			
			//if nothing else to do
			if(ss.isAlive()==false)
			{
				mStrikeSenders.remove(0);
				continue;
			}
			else  //if there are retries left
			{
				//try
				DatagramPacket p=ss.goOnce();
				if(p==null)  //if we don't get answer
					continue;
				else //if we get answer
				{
					//remove the client for the expecting reply
					mStrikeSenders.remove(0);
				}
					
			}
		}	
	}

	private boolean allAnswered() {
		if(mStrikeSenders.size()>0)
			return false;
		else return true;
	}

}
